package com.gjy.encoder.utils;

import com.gjy.encoder.security.GMCertificate;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-07-25 11:05:21
 */
public class SM2Utils {

    public static String sign(String key, String msg) {
        GMCertificate gmCertificate = new GMCertificate(decode(key), null, null, null);
        return Base64.getEncoder().encodeToString(gmCertificate.sign(getBytes(msg)));
    }

    public static boolean verify(String key, String msg, String sign) {
        GMCertificate gmCertificate = new GMCertificate(null, null, decode(key), null);
        return gmCertificate.verify(getBytes(msg), decode(sign));
    }

    public static String sign(byte[] key, byte[] msg) {
        GMCertificate gmCertificate = new GMCertificate(key, null, null, null);
        return Base64.getEncoder().encodeToString(gmCertificate.sign(msg));
    }

    public static boolean verify(byte[] key, byte[] msg, byte[] sign) {
        GMCertificate gmCertificate = new GMCertificate(null, null, key, null);
        return gmCertificate.verify(msg, sign);
    }

    public static String sign(byte[] key, byte[] signUserID, byte[] msg) {
        GMCertificate gmCertificate = new GMCertificate(key, signUserID, null, null);
        return Base64.getEncoder().encodeToString(gmCertificate.sign(msg));
    }

    public static boolean verify(byte[] key, byte[] verifyUserID, byte[] msg, byte[] sign) {
        GMCertificate gmCertificate = new GMCertificate(null, null, key, verifyUserID);
        return gmCertificate.verify(msg, sign);
    }

    public static String encrypt(String data, String key) {
        if (data == null || data.isEmpty())
            return "";
        GMCertificate gmCertificate = new GMCertificate(decode(key), null);
        return Base64.getEncoder().encodeToString(gmCertificate.encrypt(data.getBytes(StandardCharsets.UTF_8)));
    }

    public static String decrypt(String data, String key) {
        if (data == null || data.isEmpty())
            return "";
        try {
            GMCertificate gmCertificate = new GMCertificate(null, decode(key));
            return new String(gmCertificate.decrypt(decode(data)));
        } catch (Exception e) {
            return "";
        }
    }

    public static byte[] decode(String str) {
        return Base64.getDecoder().decode(str);
    }

    public static byte[] getBytes(String msg) {
        if (msg == null)
            return null;
        return msg.getBytes(StandardCharsets.US_ASCII);
    }

}
